package com.deco.back.bf.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

@Component
public class PrdPictureUploadBf {

    @Value(value = "${sys.img.root}")
    private String fileRoot;

    @Value(value = "${sys.img.directory}")
    private String fileDir;

    @Value(value = "${sys.img.prdfiles}")
    private String prdfiles;

    public void saveFile(String fileUrl){

        URL url = null;
        String filepath="";
        try {
            url = new URL(fileUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            String newpaht = fileRoot + fileDir + prdfiles;
            try{
                File file = new File(newpaht);
                if(!file.exists()){
                    file.mkdirs();
                }
            }catch(Exception ex){
                System.out.println(ex);
            }
            filepath= newpaht + fileNm(fileUrl);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filepath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String fileNm(String url){
       int lstLineIdx = url.lastIndexOf("/") + 1;
       int askIdx = url.indexOf("?");
       String fileNm = url.substring(lstLineIdx,askIdx);
       return  fileNm;
    }

    public static void main(String[] args) {
        System.out.println(fileNm("https://dts.saic-gm.com/cs/file/frontend/4433444444.jpg?token=ewwwwww"));
    }

}
